import { useEffect, useState } from 'react';
import { Card, Image, Typography, List, Row, Col, Spin, Button } from 'antd';
import axios from 'axios';
import { useNavigate, useParams, Link } from 'react-router-dom'; // 导入 Link 组件
import './index.css'; // 确保导入了 CSS 文件
import { Footer } from 'antd/es/layout/layout';

const { Meta } = Card;
const { Title } = Typography;

const SpeechSecondPage = () => {
  const [book, setBook] = useState(null);
  const [chapters, setChapters] = useState([]);
  const [loading, setLoading] = useState(true);
  const { bookId } = useParams();
  const navigate = useNavigate(); // 初始化 useNavigate，返回按钮

  useEffect(() => {
    const fetchBookDetails = async () => {
      try {
        const response = await axios.get(`/api/dialogue-books/${bookId}`);
        setBook(response.data);
      } catch (error) {
        console.error('Error fetching book details:', error);
      }
    };

    const fetchChapters = async (id) => {
      try {
        const response = await axios.get(`/api/chapters/byBookId?bookId=${id}`);
        console.log('Fetched chapters:', response.data); // 检查数据
        if (Array.isArray(response.data)) {
          setChapters(response.data);
        } else {
          console.error('Unexpected data format for chapters:', response.data);
          setChapters([]);
        }
      } catch (error) {
        console.error('Error fetching chapters:', error);
      } finally {
        setLoading(false);
      }
    };
    fetchBookDetails();
    fetchChapters(bookId); // 确保传入 bookId
  }, [bookId]);

  if (loading) {
    return (
      <div style={{ textAlign: 'center', marginTop: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!book) {
    return <div>Book not found</div>;
  }

  const handleBack = () => {
    navigate('/speech'); // 假设 FirstSpeechPage 的路径是 /first-speech-page
  };

  return (
    <div className="speech-second-page">
      <Row gutter={[24, 24]}>
        <Col span={24} style={{ marginBottom: 15 }}>
          <Button type="primary" onClick={handleBack} style={{ float: 'left' }}>
            返回
          </Button>
        </Col>
        <Col span={12}>
          <Card
            className="centered-card"
            cover={<Image 
              src={`data:image/png;base64,${book.pictureBase64}`} 
              alt={book.title}
              style={{
                width: '600px', // 设置宽度
                height: '400px', // 设置高度，与宽度相同以保持方形
                objectFit: 'cover' // 确保图片填满整个容器，并裁剪多余部分
              }} />}
            title={book.title}
            bordered={false}
            style={{ marginBottom: 15 }}
          >
            <Meta description={book.description} />
          </Card>
        </Col>
        <Col span={12}>
          <Title level={3}>Chapters</Title>
          <div className="chapter-list-container"> {/* 添加类名 */}
            <List
              itemLayout="horizontal"
              dataSource={chapters}
              renderItem={(item) => (
                <List.Item className="chapter-item"> {/* 添加类名 */}
                  <List.Item.Meta
                    title={<Link to={`/dialogue/${bookId}/sentence/${item.chapterId}`}>{item.title}</Link>}
                    description={item.etitle}
                  />
                </List.Item>
              )}
            />
          </div>
        </Col>
      </Row>
      <Footer style={{ 
        marginTop: '20px', 
        textAlign: 'center', 
        backgroundColor: '#a1daeb', 
        padding: '20px 0', 
        color: '#ffffff' 
      }}>
        <p>© 2024 Reora</p>
        <p>Contact me: <a href="mailto:981706712@qq.com">981706712@qq.com</a></p>
      </Footer>
    </div>
  );
};

export default SpeechSecondPage;